package api

import (
	"api-gatway/basic/config"
	__ "api-gatway/basic/proto"
	"api-gatway/handler/request"
	"api-gatway/utils"
	"github.com/gin-gonic/gin"
)

func Register(c *gin.Context) {
	var err error
	var form request.User

	// 根据 Content-Type Header 推断使用哪个绑定器。
	if err = c.ShouldBind(&form); err != nil {
		c.JSON(400, gin.H{
			"message": "参数有误",
			"code":    "400",
		})
		return
	}

	// 用户名是否存在，需要调用 user 服务
	userResp, err := config.UserClient.UserInFoById(c, &__.UserInfoByIdRequest{
		Account: form.Account,
	})

	if err != nil {
		c.JSON(500, gin.H{
			"message": "服务异常",
			"code":    "500",
		})
		return
	}

	if userResp.UserId != 0 {
		c.JSON(400, gin.H{
			"message": "用户名已存在",
			"code":    "400",
		})
		return
	}

	// 调用 user 服务创建用户
	_, err = config.UserClient.Createduser(c, &__.CreateduserRequest{Account: form.Account, Password: form.Password})
	if err != nil {
		c.JSON(500, gin.H{
			"message": "服务异常",
			"code":    "500",
		})
		return
	}

	c.JSON(200, gin.H{
		"message": "创建成功",
		"code":    "200",
	})

	return
}
func Login(c *gin.Context) {
	var err error
	var form request.User

	// 根据 Content-Type Header 推断使用哪个绑定器。
	if err = c.ShouldBind(&form); err != nil {
		c.JSON(400, gin.H{
			"message": "参数有误",
			"code":    "400",
			"data":    err.Error(),
		})
		return
	}
	// 用户名是否存在，需要调用 user 服务
	userResp, err := config.UserClient.UserInFoById(c, &__.UserInfoByIdRequest{
		Account: form.Account,
	})

	if err != nil {
		c.JSON(500, gin.H{
			"message": "服务异常",
			"code":    "500",
		})
		return
	}

	if userResp.UserId == 0 {
		c.JSON(400, gin.H{
			"message": "用户名不存在",
			"code":    "400",
		})
		return
	}
	token, _ := utils.GetJwtToken(int64(form.Id))
	c.JSON(200, gin.H{
		"message": "登录成功",
		"code":    "200",
		"data": gin.H{
			"token":   token,
			"user_id": userResp.UserId,
		},
	})
	return
}
